package com.ease.concurrent.threadpool.mrbird;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: chenhs
 * @date: Created in 21:51 2020/3/14
 *
 * 1）
 * 使用顺序：corePoolSize ->　workQueue -> maximumPoolSize
 * 当Queue满了之后都会创建非核心线程；数量(maximumPoolSize-corePoolSize)
 * 所以pool可接受的最大任务数为 maximumPoolSize + workQueue.size
 *
 * 2）
 * 10s的keepAliveTime可以快照dump中观察得到
 *
 **/
public class SizeTest {
    public static void main(String[] args) {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 2, 10, TimeUnit.SECONDS
                , new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.AbortPolicy());
        System.out.println("线程创建完毕！");

        threadPoolExecutor.execute(() -> sleep(50));
        threadPoolExecutor.execute(() -> sleep(50));
        threadPoolExecutor.execute(() -> sleep(50));
        threadPoolExecutor.execute(() -> sleep(50));


        int activeCount = -1;
        int queueCount = -1;
        while (true) {
            if (activeCount != threadPoolExecutor.getActiveCount() || queueCount != threadPoolExecutor.getQueue().size()) {
                System.out.println("活跃线程个数：" + threadPoolExecutor.getActiveCount());
                System.out.println("核心线程个数：" + threadPoolExecutor.getCorePoolSize());
                System.out.println("队列线程个数：" + threadPoolExecutor.getQueue().size());
                System.out.println("最大线程数：" + threadPoolExecutor.getMaximumPoolSize());
                System.out.println("----------------------------》");
                activeCount = threadPoolExecutor.getActiveCount();
                queueCount = threadPoolExecutor.getQueue().size();
            }
        }
    }

    private static void sleep(int value) {
        try {
            System.out.println(Thread.currentThread().getName() + "线程执行sleep方法");
            TimeUnit.SECONDS.sleep(value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
